﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace ConverToDNS
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            this.groupBox2.Enabled = true;
        }
        object[] cityArray = new object[] {
            "安徽|AnHui",
            "北京|BeiJing",
            "重庆|ChongQing",
            "福建|FuJian",
            "甘肃|GanSu",
            "广东|GuangDong",
            "广西|GuangXi",
            "贵州|GuiZhou",
            "海南|HaiNan",
            "河北|HeBei",
            "河南|HeNan",
            "黑龙江|HeiLongJiang",
            "湖北|HuBei",
            "湖南|HuNan",
            "吉林|JiLin",
            "江苏|JiangSu",
            "江西|JiangXi",
            "辽宁|LiaoNing",
            "内蒙古|NeiMengGu",
            "宁夏|NingXia",
            "青海|QingHai",
            "山东|ShanDong",
            "山西|SShanXi",
            "陕西|ShanXi",
            "上海|ShangHai",
            "四川|SiChuan",
            "台湾|TaiWan",
            "天津|TianJin",
            "西藏|XiZang",
            "新疆|XinJiang",
            "云南|YunNan",
            "浙江|ZheJiang",
            "香港|XiangGang",
            "澳门|AoMen",
            "所有|All"
        };
        object[] lineArray = new object[] {
        "联通|cnc","电信|telcom","铁通|tietong","移动|mobile","教育网|cernet","所有|All"
        };
        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            province.Text = "请选择省份";
            line.Text = "请选择线路";
            this.groupBox2.Enabled = false;
        }
        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = "c:\\";
            openFileDialog.Filter = "ACCESS文件*.mdb|*.mdb";
            openFileDialog.RestoreDirectory = true;
            openFileDialog.FilterIndex = 1;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = openFileDialog.FileName;
            }
        }
        public List<Ip> ReadAll(string path)
        {
            List<Ip> ipList = new List<Ip>();
            try
            {
                string strConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";";
                OleDbConnection odcConnection = new OleDbConnection(strConn);
                odcConnection.Open();
                OleDbCommand odCommand = odcConnection.CreateCommand();
                odCommand.CommandText = "select 字段1,字段2,字段3 from ip";
                OleDbDataAdapter adapter = new OleDbDataAdapter(odCommand);
                DataSet data = new DataSet();
                adapter.Fill(data);
                if (data != null && data.Tables.Count > 0)
                {
                    DataRowCollection rows = data.Tables[0].Rows;
                    foreach (DataRow row in rows)
                    {
                        Ip ip = new Ip();
                        ip.IpStart = row["字段1"].ToString();
                        ip.IpEnd = row["字段2"].ToString();
                        ip.Content = row["字段3"].ToString();
                        ipList.Add(ip);
                    }
                }
                odcConnection.Close();
                return ipList;
            }
            catch (Exception ex)
            {
                listBox1.Items.Insert(0, "数据库操作:" + ex.Message);
                return ipList;
            }
        }
        private void processeIP(List<Ip> ipListAll, string city, string line)
        {
            string[] scityArray, slineArray, ipStartArray, ipEndArray;
            string ipStart, ipEnd;
            scityArray = city.Split('|');
            slineArray = line.Split('|');
            try
            {
                List<Ip> ipList1 = ipListAll.Where(ip => ip.Content.Contains(scityArray[0]) && ip.Content.Contains(slineArray[0])).ToList();
                StringBuilder buffer = new StringBuilder();
                buffer.AppendLine("acl \"" + scityArray[1] + "." + slineArray[1] + "\"{");
                foreach (Ip ip in ipList1)
                {
                    ipStart = ip.IpStart.ToString();
                    ipEnd = ip.IpEnd.ToString();
                    ipStartArray = ipStart.Split('.');
                    ipEndArray = ipEnd.Split('.');
                    //完整IP1.2.3.4
                    if (ipStartArray[0] == ipEndArray[0] && ipStartArray[1] == ipEndArray[1] && ipStartArray[2] == ipEndArray[2] && ipStartArray[3] == ipEndArray[3])
                        buffer.AppendLine(ipStart.ToString() + ";");
                    //24位掩码地址1.2.3.0-1.2.3.255
                    else if (ipStartArray[0] == ipEndArray[0] && ipStartArray[1] == ipEndArray[1] && ipStartArray[2] == ipEndArray[2] && ipStartArray[3] == "0" && ipEndArray[3] == "255")
                        buffer.AppendLine(ipStart.ToString() + "/24;");
                    //16位掩码地址1.2.0.0-1.2.255.255
                    else if (ipStartArray[0] == ipEndArray[0] && ipStartArray[1] == ipEndArray[1] && ipStartArray[2] == "0" && ipEndArray[2] == "255" && ipStartArray[3] == "0" && ipEndArray[3] == "255")
                        buffer.AppendLine(ipStart.ToString() + "/16;");
                    //8位掩码地址1.0.0.0-1.255.255.255.255
                    else if (ipStartArray[0] == ipEndArray[0] && ipStartArray[1] == "0" && ipEndArray[1] == "255" && ipStartArray[2] == "0" && ipEndArray[2] == "255" && ipStartArray[3] == "0" && ipEndArray[3] == "255")
                        buffer.AppendLine(ipStart.ToString() + "/8;");
                    //第四项数据不同12.13.10.14-12.13.10.48
                    else if (ipStartArray[0] == ipEndArray[0] && ipStartArray[1] == ipEndArray[1] && ipStartArray[2] == ipEndArray[2] && int.Parse(ipEndArray[3].ToString()) > int.Parse(ipStartArray[3].ToString()))
                        for (int i = int.Parse(ipStartArray[3].ToString()); i <= int.Parse(ipEndArray[3].ToString()); i++)
                            buffer.AppendLine(ipStartArray[0] + "." + ipStartArray[1] + "." + ipStartArray[2] + "." + i.ToString() + ";");
                    //第三项数据不同12.13.10.0-12.12.15.255
                    else if (ipStartArray[0] == ipEndArray[0] && ipStartArray[1] == ipEndArray[1] && int.Parse(ipEndArray[2].ToString()) > int.Parse(ipStartArray[2].ToString()) && ipStartArray[3] == "0" && ipEndArray[3] == "255")
                        for (int i = int.Parse(ipStartArray[2].ToString()); i <= int.Parse(ipEndArray[2].ToString()); i++)
                            buffer.AppendLine(ipStartArray[0] + "." + ipStartArray[1] + "." + i.ToString() + "." + ipStartArray[3] + "/24;");
                    //第二项数据不同12.13.0.0-12.18.255.255
                    else if (ipStartArray[0] == ipEndArray[0] && int.Parse(ipEndArray[1].ToString()) > int.Parse(ipStartArray[1].ToString()) && ipStartArray[2] == "0" && ipEndArray[2] == "255" && ipStartArray[3] == "0" && ipEndArray[3] == "255")
                        for (int i = int.Parse(ipStartArray[1].ToString()); i <= int.Parse(ipEndArray[1].ToString()); i++)
                            buffer.AppendLine(ipStartArray[0] + "." + i.ToString() + "." + ipStartArray[2] + "." + ipStartArray[3] + "/16;");
                    //第一项数据不同12.0.0.0-18.255.255.255
                    else if (int.Parse(ipEndArray[0].ToString()) > int.Parse(ipStartArray[0].ToString()) && ipStartArray[1] == "0" && ipEndArray[1] == "255" && ipStartArray[2] == "0" && ipEndArray[2] == "255" && ipStartArray[3] == "0" && ipEndArray[3] == "255")
                        for (int i = int.Parse(ipStartArray[0].ToString()); i <= int.Parse(ipEndArray[0].ToString()); i++)
                            buffer.AppendLine(i.ToString() + "." + ipStartArray[1] + "." + ipStartArray[2] + "." + ipStartArray[3] + "/8;");
                    //后三项数据不同12.13.14.15-12.15.18.19 or 12.13.14.15-12.15.18.8
                    else if (ipStartArray[0] == ipEndArray[0] && int.Parse(ipEndArray[1].ToString()) >= int.Parse(ipStartArray[1].ToString()) && int.Parse(ipEndArray[2].ToString()) >= int.Parse(ipStartArray[2].ToString()) || int.Parse(ipEndArray[2].ToString()) <= int.Parse(ipStartArray[2].ToString()) && int.Parse(ipEndArray[3].ToString()) >= int.Parse(ipStartArray[3].ToString()) || int.Parse(ipEndArray[3].ToString()) <= int.Parse(ipStartArray[3].ToString()))
                    {
                        int tmpi1 = 0, tmpj1 = 0, tmpk1 = 0, tmpi2 = 0, tmpj2 = 0, tmpk2 = 0;
                        for (int i = int.Parse(ipStartArray[1].ToString()); i <= int.Parse(ipEndArray[1].ToString()); i++)
                        {
                            if (i == int.Parse(ipStartArray[1].ToString()))
                            {
                                tmpi1 = int.Parse(ipStartArray[2].ToString());
                                if (tmpi1 == 0)
                                    tmpi1++;
                                for (int j = int.Parse(ipStartArray[2].ToString()); j <= int.Parse(ipEndArray[2].ToString()); j++)
                                {
                                    if (j == int.Parse(ipStartArray[2].ToString()))
                                    {
                                        tmpj1 = int.Parse(ipStartArray[3].ToString());
                                        if (tmpj1 == 0)
                                            tmpj1++;
                                        for (int k = tmpj1; k < 255; k++)
                                            buffer.AppendLine(ipStartArray[0] + "." + i.ToString() + "." + j.ToString() + "." + k.ToString() + ";");
                                    }
                                    else if (i == int.Parse(ipEndArray[2].ToString()))
                                    {
                                        tmpk1 = int.Parse(ipEndArray[3].ToString());
                                        if (tmpk1 == 0)
                                            tmpk1++;
                                        for (int k = 1; k < tmpk1; k++)
                                            buffer.AppendLine(ipStartArray[0] + "." + i.ToString() + "." + j.ToString() + "." + k.ToString() + ";");

                                    }
                                    else
                                    {
                                        buffer.AppendLine(ipStartArray[0] + "." + ipStartArray[1] + "." + i.ToString() + "." + "0/24;");
                                    }
                                }
                            }
                            else if (i == int.Parse(ipEndArray[2].ToString()))
                            {
                                tmpi2 = int.Parse(ipStartArray[2].ToString());
                                if (tmpi2 == 0)
                                    tmpi2++;
                                for (int j = int.Parse(ipStartArray[2].ToString()); j <= int.Parse(ipEndArray[2].ToString()); j++)
                                {
                                    if (j == int.Parse(ipStartArray[2].ToString()))
                                    {
                                        tmpj2 = int.Parse(ipStartArray[3].ToString());
                                        if (tmpj2 == 0)
                                            tmpj2++;
                                        for (int k = tmpj2; k < 255; k++)
                                            buffer.AppendLine(ipStartArray[0] + "." + i.ToString() + "." + j.ToString() + "." + k.ToString() + ";");
                                    }
                                    else if (i == int.Parse(ipEndArray[2].ToString()))
                                    {
                                        tmpk2 = int.Parse(ipEndArray[3].ToString());
                                        if (tmpk2 == 0)
                                            tmpk2++;
                                        for (int k = 1; k < tmpk2; k++)
                                            buffer.AppendLine(ipStartArray[0] + "." + i.ToString() + "." + j.ToString() + "." + k.ToString() + ";");

                                    }
                                    else
                                    {
                                        buffer.AppendLine(ipStartArray[0] + "." + ipStartArray[1] + "." + i.ToString() + "." + "0/24;");
                                    }
                                }
                            }
                            else
                            {
                                buffer.AppendLine(ipStartArray[0] + "." + ipStartArray[1] + "." + "0.0/16;");
                            }
                        }
                    }
                    else
                        writeFile("无法识别" + ipStart + "--" + ipEnd, "error");
                }
                buffer.AppendLine("};");
                //
                writeFile(buffer.ToString(), scityArray[1]);
                listBox1.Items.Insert(0, scityArray[0] + ":" + slineArray[1] + "--生成完成");
                listBox1.Refresh();
            }
            catch (Exception ex)
            {
                listBox1.Items.Insert(0, "文件处理：" + ex.Message);
            }
        }
        private void writeFile(string readme, string fileName)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "acl";
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            StreamWriter log = new StreamWriter(path + "\\" + fileName + ".acl", true);
            log.WriteLine(readme);
            log.Close();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            Thread th = new Thread(new ThreadStart(delegate
            {
                if (string.IsNullOrEmpty(textBox1.Text))
                    MessageBox.Show("请选择数据库文件");
                else
                {
                    button1.Text = "生成中";
                    this.button1.Enabled = false;
                    this.groupBox1.Enabled = false;
                    this.groupBox2.Enabled = false;
                    this.groupBox3.Enabled = false;
                    List<Ip> ipListAll = this.ReadAll(textBox1.Text);
                    if (radioButton1.Checked == false && radioButton2.Checked == true)
                    {
                        if (province.Text == "请选择省份" && line.Text == "请选择线路")
                            MessageBox.Show("请选择省份或者线路");
                        else if (line.Text == "请选择线路" || line.Text == "所有|All")
                        {
                            MessageBox.Show("由于你没有选择线路，将会生成所有线路");
                            for (int i = 0; i < lineArray.Length - 1; i++)
                            {
                                processeIP(ipListAll, province.Text, (string)lineArray[i]);
                            }
                        }
                        else if (province.Text == "请选择省份" || province.Text == "所有|All")
                        {
                            MessageBox.Show("由于你没有选择省份，将会生成所有省份");
                            for (int i = 0; i < cityArray.Length - 1; i++)
                            {
                                processeIP(ipListAll, (string)cityArray[i], line.Text);
                            }
                        }
                        else
                            processeIP(ipListAll, province.Text, line.Text);
                    }
                    else
                    {
                        for (int i = 0; i < cityArray.Length - 1; i++)
                            for (int j = 0; j < lineArray.Length - 1; j++)
                                processeIP(ipListAll, (string)cityArray[i], (string)lineArray[j]);
                    }
                    button1.Text = "生成";
                    MessageBox.Show("全部生成完成");
                    this.button1.Enabled = true;
                    this.groupBox1.Enabled = true;
                    this.groupBox3.Enabled = true;
                }
            }));
            th.Start();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "acl";
            if (Directory.Exists(path))
                Directory.Delete(path, true);
            province.Items.AddRange(cityArray);
            line.Items.AddRange(lineArray);
        }
    }
    public class Ip
    {
        public string IpStart { get; set; }
        public string IpEnd { get; set; }
        public string Content { get; set; }
    }
}
